/**
 * @file UserManagement.vue
 * @description 用户管理组件，用于管理系统用户
 * @created 2024-06-01
 */

<template>
  <div class="user-management">
    <div class="header">
      <h1 class="title">用户管理</h1>
      <div class="actions">
        <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名/姓名/学院/班级"
          clearable
          @clear="handleSearch"
          @input="handleSearchInput"
          style="width: 300px; margin-left: 16px;"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="handleSearch"></el-button>
          </template>
        </el-input>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="userList"
      border
      stripe
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column prop="realName" label="姓名" min-width="120"></el-table-column>
      <el-table-column prop="role" label="角色" min-width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.role === 'school_admin'" type="danger">校级管理员</el-tag>
          <el-tag v-else-if="scope.row.role === 'college_admin'" type="warning">学院管理员</el-tag>
          <el-tag v-else-if="scope.row.role === 'class_admin'" type="success">班级管理员</el-tag>
          <el-tag v-else-if="scope.row.role === 'teacher'" type="info">教师</el-tag>
          <el-tag v-else-if="scope.row.role === 'student'" type="primary">学生</el-tag>
          <span v-else>{{ scope.row.role }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="collegeName" label="学院" min-width="150"></el-table-column>
      <el-table-column prop="className" label="班级" min-width="150"></el-table-column>
      <el-table-column prop="phone" label="电话" min-width="150"></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
      <el-table-column prop="lastLogin" label="最后登录时间" min-width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            :disabled="scope.row.role === 'school_admin'"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="warning"
            @click="handleResetPassword(scope.row)"
          >重置密码</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.role === 'school_admin'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="40%"
      @close="resetForm"
    >
      <el-form
        :model="userForm"
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
        style="max-width: 500px; margin: 0 auto;"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="校级管理员" value="school_admin"></el-option>
            <el-option label="学院管理员" value="college_admin"></el-option>
            <el-option label="班级管理员" value="class_admin"></el-option>
            <el-option label="教师" value="teacher"></el-option>
            <el-option label="学生" value="student"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学院" prop="collegeId">
          <el-select 
            v-model="userForm.collegeId" 
            placeholder="请选择学院" 
            style="width: 100%"
            @change="handleCollegeChange"
          >
            <el-option 
              v-for="item in collegeList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId" v-if="userForm.role === 'student' || userForm.role === 'class_admin'">
          <el-select v-model="userForm.classId" placeholder="请选择班级" style="width: 100%">
            <el-option 
              v-for="item in classList" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
      </template>
    </el-dialog>

    <!-- 重置密码确认对话框 -->
    <el-dialog
      title="重置密码"
      v-model="resetPasswordDialogVisible"
      width="30%"
    >
      <p>确定要重置该用户的密码吗？密码将被重置为默认密码。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmResetPassword">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除用户"
      v-model="deleteDialogVisible"
      width="30%"
    >
      <p>确定要删除该用户吗？此操作不可恢复！</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="danger" @click="confirmDelete">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, addUser, updateUser, deleteUser, resetUserPassword, toggleUserStatus } from '@/api/user'
import { getCollegeList, getClassesByCollege } from '@/api/college'

export default {
  name: 'UserManagement',
  setup() {
    // 数据加载状态
    const loading = ref(false)
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 用户列表数据
    const userList = ref([])
    
    // 搜索关键词
    const searchKeyword = ref('')
    
    // 学院和班级数据
    const collegeList = ref([])
    const classList = ref([])
    
    // 对话框控制
    const dialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    const resetPasswordDialogVisible = ref(false)
    const deleteDialogVisible = ref(false)
    
    // 当前操作的用户ID
    const currentUserId = ref(null)

    // 表单引用
    const userFormRef = ref(null)
    
    // 用户表单数据
    const userForm = reactive({
      id: '',
  username: '',
      realName: '',
      role: '',
      collegeId: '',
      classId: '',
      phone: '',
      email: '',
  password: '',
      status: 1
    })
    
    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      collegeId: [
        { required: true, message: '请选择学院', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
          if (dialogType.value === 'add' && !value) {
            callback(new Error('请输入密码'))
          } else {
            callback()
          }
        }}
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }

    // 获取用户列表
    const fetchUserList = async () => {
  loading.value = true
  try {
        const params = {
          page: currentPage.value,
          limit: pageSize.value,
          keyword: searchKeyword.value
        }
        const res = await getUserList(params)
        userList.value = res.data.list
        total.value = res.data.total
  } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

    // 获取学院列表
    const fetchCollegeList = async () => {
  try {
        const res = await getCollegeList()
        collegeList.value = res.data
      } catch (error) {
        console.error('获取学院列表失败:', error)
        ElMessage.error('获取学院列表失败')
      }
    }

    // 根据学院获取班级列表
    const fetchClassList = async (collegeId) => {
      if (!collegeId) {
        classList.value = []
        return
      }
      try {
        const res = await getClassesByCollege(collegeId)
        classList.value = res.data
  } catch (error) {
        console.error('获取班级列表失败:', error)
        ElMessage.error('获取班级列表失败')
  }
}

    // 学院选择变化处理
    const handleCollegeChange = (collegeId) => {
      userForm.classId = '' // 重置班级选择
      fetchClassList(collegeId)
    }

    // 添加用户
    const handleAddUser = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
    }

    // 编辑用户
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      nextTick(() => {
        Object.keys(userForm).forEach(key => {
          userForm[key] = row[key]
        })
        // 班级和学院数据处理
        userForm.collegeId = row.collegeId
        userForm.classId = row.classId
        fetchClassList(row.collegeId)
      })
      dialogVisible.value = true
    }

    // 重置密码
    const handleResetPassword = (row) => {
      currentUserId.value = row.id
      resetPasswordDialogVisible.value = true
}

    // 确认重置密码
    const confirmResetPassword = async () => {
      try {
        await resetUserPassword(currentUserId.value)
        ElMessage.success('密码重置成功')
        resetPasswordDialogVisible.value = false
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置密码失败')
      }
    }

    // 删除用户
    const handleDelete = (row) => {
      if (row.role === 'school_admin') {
        ElMessage.warning('不能删除校级管理员账户')
        return
      }
      currentUserId.value = row.id
      deleteDialogVisible.value = true
}

    // 确认删除
    const confirmDelete = async () => {
      try {
        await deleteUser(currentUserId.value)
        ElMessage.success('删除用户成功')
        deleteDialogVisible.value = false
        fetchUserList()
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败')
      }
}

    // 状态变更
    const handleStatusChange = async (row) => {
      try {
        await toggleUserStatus(row.id, row.status)
        ElMessage.success(`用户状态已${row.status === 1 ? '启用' : '禁用'}`)
      } catch (error) {
        console.error('更新用户状态失败:', error)
        ElMessage.error('更新用户状态失败')
        // 恢复状态
        row.status = row.status === 1 ? 0 : 1
      }
}

    // 提交表单
    const submitForm = () => {
      userFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              await addUser(userForm)
              ElMessage.success('添加用户成功')
            } else {
              await updateUser(userForm)
              ElMessage.success('更新用户成功')
            }
            dialogVisible.value = false
            fetchUserList()
          } catch (error) {
            console.error('保存用户失败:', error)
            ElMessage.error('保存用户失败')
          }
    } else {
          return false
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      if (userFormRef.value) {
        userFormRef.value.resetFields()
      }
      Object.keys(userForm).forEach(key => {
        if (key === 'status') {
          userForm[key] = 1
    } else {
          userForm[key] = ''
    }
      })
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchUserList()
}

    // 输入框内容变化时处理
    const handleSearchInput = () => {
      if (searchKeyword.value === '') {
        handleSearch()
      }
    }

    // 分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchUserList()
    }

    // 当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchUserList()
}

    // 组件挂载时加载数据
    onMounted(() => {
      fetchUserList()
      fetchCollegeList()
    })

    return {
      loading,
      userList,
      currentPage,
      pageSize,
      total,
      searchKeyword,
      dialogVisible,
      dialogType,
      resetPasswordDialogVisible,
      deleteDialogVisible,
      userForm,
      rules,
      userFormRef,
      collegeList,
      classList,
      handleAddUser,
      handleEdit,
      handleDelete,
      handleResetPassword,
      handleStatusChange,
      handleSearch,
      handleSearchInput,
      handleSizeChange,
      handleCurrentChange,
      submitForm,
      resetForm,
      confirmResetPassword,
      confirmDelete,
      handleCollegeChange
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: 500;
  margin: 0;
}

.actions {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 